<template>
    <div class="qiniu">
        <input hidden type="file" :class="className" name="myfile" @change="uploads" :id="className" :accept="accept"
               :multiple="multiple" :disabled="disabled"/>
        <label :class="labelClass" :for="className">{{isShort ? '上传':'点击上传'}}</label>
        <div class="item" v-if="showProgress && beginUpload">
          <div>
            <div class="outProgress">
              <div class="progress" :style="{width: total.percent+'%'}"></div>
            </div>
            <b>{{total.percent}}%</b>
          </div>
          <span><i class="iconfont icon-ziliao"></i>{{fileName}}</span>
        </div>
    </div>
</template>

<script>
    import * as qiniu from 'qiniu-js'
    import {mapState} from 'vuex'
    import {randomChar} from "../../util";

    export default {
        name: "Qiniu",
        data() {
            return {
              urls: [],
              fileName:'资料文件上传',
              beginUpload:false,
              total:{
                percent:0
              },
              uploadFileNames:[],
              fileLength:1
            }
        },
        props: ['className', 'accept', 'multiple', 'prop','disabled','showProgress','labelClass','isShort','isUrl'],
      computed:mapState({
        qiniuToken: state => state.user.qiniuToken,
      }),
        methods: {
            uploads() {
              let files = document.querySelector('.' + this.className).files;
                let filesArr = Array.from(files);
                this.fileLength = filesArr.length;
                this.$indicator.open();
                filesArr.map((file) => {
                      return this.upload(file)
                  });
            },
            upload(file) {
              this.fileName = file.name;
              let uploadFileName = randomChar(12) + file.name.slice(file.name.lastIndexOf('.'));
              let that = this;
                let uploadAccept = null;
                if (this.accept) {
                    uploadAccept = this.accept.split(',');
                }
                let observer = {
                    next(res) {
                      that.total = res.total;
                    },
                    error(err) {
                      that.$indicator.close();
                      that.$toast(err,this.$toast);
                      that.$store.dispatch('setQiniuTokenAction');
                    },
                    complete(res) {
                      that.uploadFileNames.push(uploadFileName);
                      if(that.uploadFileNames.length===that.fileLength){
                        that.$indicator.close();
                      }
                      if(that.isUrl){
                        that.$api.uploadSignUrl({name:res.key}).then((res2)=>{
                          that.urls.push(res2.data);
                        });
                      }else {
                        that.urls.push(res.key);
                      }
                    }
                };
                let putExtra = {
                    fname: file.name,
                    params: {},
                    mimeType: uploadAccept
                    // mimeType:  null
                };
                let config = {
                    useCdnDomain: true,
                };
              if(this.qiniuToken){
                  let observable = qiniu.upload(file,uploadFileName, this.qiniuToken, putExtra, config);
                  observable.subscribe(observer); // 上传开始
                  this.beginUpload = true;
                }else {
                  this.$store.dispatch('setQiniuTokenAction').then((res)=>{
                    let observable = qiniu.upload(file,uploadFileName, res.data, putExtra, config);
                    observable.subscribe(observer); // 上传开始
                    this.beginUpload = true;
                  }).catch((err)=>{
                    this.$msg(err,this.$toast);
                    this.$indicator.close();
                  })
                }
            },
        },
        watch: {
            urls: {
                handler(newValue) {
                  if(newValue.length===0){
                    return;
                  }
                  if(this.multiple && this.fileLength>1){
                    if(newValue.length===this.fileLength){
                      this.$emit('upload', newValue,this.prop, this.uploadFileNames);
                      this.urls = [];
                      this.uploadFileNames = [];
                      document.querySelector('.' + this.className).value = '';
                    }
                  }else {
                    this.$emit('upload', newValue[0],this.prop,this.uploadFileNames[0]);
                    this.urls = [];
                    this.uploadFileNames = [];
                    document.querySelector('.' + this.className).value = '';
                  }
                },
                deep: true
            }
        }
    }
</script>

<style lang="scss" scoped>
    label {
        display: inline-block;
        width:180px;
        height:46px;
        background:rgba(231,31,24,1);
        border-radius:4px;
        font-size: 18px;
        /*color: #FFF;*/
        border: none;
        outline: none;
        cursor: pointer;
        text-align: center;
        line-height: 46px;
    }

    label:hover {
        opacity: 0.7;
    }
   .item{
     font-size:14px;
     line-height: 14px;
     margin: 20px 0 0 0;
     color: black;
     >span{
       display: block;
       margin: 20px 0 0 0;
       text-align: left;
     }
     >div{
       width: 200%;
       height: 20px;
       position: relative;
       overflow: hidden;
       .outProgress{
         width:142px;
         height:4px;
         /*background:rgba(245,245,245,1);*/
         background: #fff;
         border-radius:2px;
         margin: 13px 0 0 0;
         float: left;
         .progress{
           height:4px;
           background:rgba(243,152,0,1);
           border-radius:2px;
         }
       }
       b{
         float: left;
         line-height: 20px;
         margin: 0 0 0 10px;
       }
     }
   }


</style>
